window.izwebz = [];
;(function($, scope){
    scope['core'] = {
        facebook : {
            userInformation : {
            	id: null,
                email: null,
                profile_picture: null,
                education: [],
                first_name: null,
                last_name: null,
                name: null,
                gender: null,
                hometown: [],
                id: null,
                link: null,
                locale: null,
                location: [],
                timezone: null,
                updated_time: null,
                username: null,
                verified: null,
                work: []
            },
            init : function(id) {
                var self = this;
                window.fbAsyncInit = function () {
                    FB.init({
                        appId: id,
                        status: true,
                        cookie: true,
                        xfbml: true
                    });
                };
            },
            isLogin : function() {
                var self = this;
                FB.getLoginStatus(function(response){
                    if(response.status === 'connected') {
                        $.post(ajax_script.ajaxurl,{
                            action: "checkFaceBookUser",
                            userID: response.authResponse.userID,
                            token: response.authResponse.accessToken 
                        },function(check){
                            if(check.success == true){
                                self.addUser(response.authResponse.userID);
                            }else{
                                return false;
                            }
                        });
                    }
                });
            },
            login : function() {
                var self = this;
                if(self.isLogin() == true){
                    window.location.reload();
                }else{
                    FB.login(function(response) {
                        response = response.authResponse;
                        if(response.userID){
                            self.addUser(response.userID);
                        }
                    },{scope: 'email'});
                }
            },
            logout : function() {
                FB.getLoginStatus(function(response){
                    if(response.status === 'connected') {
                        response = response.authResponse;
                        if(response.userID){
                            $.post(ajax_script.ajaxurl,{
                                action: "updateStatusFaceBookUser",
                                userID: response.userID
                            },function(update){
                                if(update.success == true){
                                   window.location.reload();
                                }
                            });
                        }
                    }
                });
            },
            postFeed: function(title,caption,description,link,thumbnail)
            {
                FB.ui({
                    method: 'feed',
                    name: title,
                    caption: caption,
                    description: (description),
                    link: link,
                    picture: thumbnail
                },function(response) {
                    if(response && response.post_id) {
                      alert('Cảm ơn bạn đã chia sẽ bài viết này');
                    }
                    return false;
                });
            },
            addUser : function(id) {
            	var self = this.userInformation;
            	var i = 0;
                var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?/;
                FB.api("/"+id,function (response) {
                	if(response.id !=null){
                		self.id = response.id;
                        self.profile_picture = "https://graph.facebook.com/"+response.id+"/picture?width=32&height=32";
                        self.email = response.email;
	                	self.first_name = response.first_name;
	                	self.last_name = response.last_name;
	                	self.gender = response.gender;
	                	self.link = response.link;
	                	self.locale = response.locale;
	                	self.name = response.name;
	                	self.timezone = response.timezone;
	                	self.updated_time = response.updated_time;
	                	self.username = response.username;
	                	self.verified = response.verified;
                        if(izwebz.core.support.isset(response.education)){
                            $.each(response.education,function(x,y){
                                 var saveEducation;
                                 if(izwebz.core.support.isset(y.school)){
                                    saveEducation = "School:"+y.school.name;
                                 }
                                 if(izwebz.core.support.isset(y.type)){
                                    saveEducation = saveEducation+"|Type:"+y.type;
                                 }
                                 self.education[x] = saveEducation;
                            });
                        }
                        if(izwebz.core.support.isset(response.hometown)){
                            $.each(response.hometown,function(x,y){
                                if(!numberRegex.test(y)){
                                    self.hometown[i] = y;
                                }
                                i++;
                            });
                            i=0;
                        }
                        if(izwebz.core.support.isset(response.location)){
                            $.each(response.location,function(x,y){
                                if(!numberRegex.test(y)){
                                        self.location[i] = y;
                                }
                                i++;
                            });
                        }
                        if(izwebz.core.support.isset(response.work)){
                            $.each(response.work,function(x,y){
                                var saveWork;
                                if(izwebz.core.support.isset(y.employer)){
                                    saveWork = "Employer:"+y.employer.name;
                                }
                                if(izwebz.core.support.isset(y.location)){
                                    saveWork = saveWork+"|Location:"+y.location.name;
                                }
                                if(izwebz.core.support.isset(y.position)){
                                    saveWork = saveWork+"|Position:"+y.position.name;
                                }
                                if(izwebz.core.support.isset(y.start_date)){
                                    saveWork = saveWork+"|StartDate:"+y.start_date;
                                }
                                self.work[x] = saveWork;
                            });
                        }
	              
	                	$.post(ajax_script.ajaxurl,{
							action: "saveUserProfile",
							data: self
						},function(data){
							if(data.success == true){
                                window.location.reload();
							}
						});
                	}else{
                		// Error
                	}
                });
            },
        },
        support : {
            isset: function(val){
                return (typeof(val) != 'undefined');
            },
            ltrim: function(str, chars) {
                chars = chars || "\\s";
                return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
            },
            crypte: function(val,code){
                var clepriv = 9270456321012741087;
                var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?/;
                var ascii = 657;
                if(!numberRegex.test(code)){
                    for(var i=1;i<=code.length;i++){
                        ascii+=this.ord(this.substr(code,i,1));
                    }
                    var tmp = clepriv * (ascii * this.strlen(code));
                }else{
                    var tmp = clepriv * code;
                }
                return Math.round((val*tmp/65198124489521632982)+5746);
            },
            decrypte: function(val,code){
                var clepriv = 9270456321012741087;
                var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?/;
                var ascii = 657;
                if(!numberRegex.test(code)){
                    for(var i=1;i<=code.length;i++){
                        ascii+=this.ord(this.substr(code,i,1));
                    }
                    var tmp = clepriv * (ascii * this.strlen(code));
                }else{
                    var tmp = clepriv * code;
                }
                return Math.round((val-5746)*65198124489521632982/tmp);
            },
            sha1: function(str) {
                var rotate_left = function (n, s) {
                    var t4 = (n << s) | (n >>> (32 - s));
                    return t4;
                };
                var cvt_hex = function (val) {
                var str = "";
                var i;
                var v;

                for(i = 7; i >= 0; i--){
                    v = (val >>> (i * 4)) & 0x0f;
                    str += v.toString(16);
                }
                    return str;
                };

                var blockstart;
                var i, j;
                var W = new Array(80);
                var H0 = 0x67452301;
                var H1 = 0xEFCDAB89;
                var H2 = 0x98BADCFE;
                var H3 = 0x10325476;
                var H4 = 0xC3D2E1F0;
                var A, B, C, D, E;
                var temp;

                str = unescape(encodeURIComponent(str));
                var str_len = str.length;
                var word_array = [];
                for (i = 0; i < str_len - 3; i += 4) {
                    j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
                    word_array.push(j);
                }

                switch (str_len % 4) {
                    case 0:
                        i = 0x080000000;
                        break;
                    case 1:
                        i = str.charCodeAt(str_len - 1) << 24 | 0x0800000;
                        break;
                    case 2:
                        i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000;
                        break;
                    case 3:
                        i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << 8 | 0x80;
                        break;
                }

                word_array.push(i);

                while ((word_array.length % 16) != 14) {
                    word_array.push(0);
                }

                word_array.push(str_len >>> 29);
                word_array.push((str_len << 3) & 0x0ffffffff);
                for(blockstart = 0; blockstart < word_array.length; blockstart += 16) {
                    for (i = 0; i < 16; i++) {
                        W[i] = word_array[blockstart + i];
                    }
                for(i = 16; i <= 79; i++) {
                    W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
                }

                A = H0;
                B = H1;
                C = H2;
                D = H3;
                E = H4;

                for (i = 0; i <= 19; i++) {
                    temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                for (i = 20; i <= 39; i++) {
                    temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                for (i = 40; i <= 59; i++) {
                    temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                for (i = 60; i <= 79; i++) {
                    temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotate_left(B, 30);
                    B = A;
                    A = temp;
                }

                    H0 = (H0 + A) & 0x0ffffffff;
                    H1 = (H1 + B) & 0x0ffffffff;
                    H2 = (H2 + C) & 0x0ffffffff;
                    H3 = (H3 + D) & 0x0ffffffff;
                    H4 = (H4 + E) & 0x0ffffffff;
                }

                temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
                return temp.toLowerCase();
            },
            ord: function(string) {
                var str = string + '',
                code = str.charCodeAt(0);
                if(0xD800 <= code && code <= 0xDBFF){
                    var hi = code;
                if(str.length === 1) {
                    return code;
                }
                var low = str.charCodeAt(1);
                return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                }
                if (0xDC00 <= code && code <= 0xDFFF) {
                    return code;
                }
                return code;
            },
            substr: function(str, start, len){
                var i = 0,allBMP = true,es = 0,el = 0,se = 0,ret = '';str += '';
                var end = str.length;
                var unicode_semantics = 'on';
                switch(unicode_semantics) {
                case 'on':
                    for (i = 0; i < str.length; i++) {
                        if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
                            allBMP = false;
                            break;
                        }
                    }

                    if (!allBMP) {
                        if (start < 0) {
                            for (i = end - 1, es = (start += end); i >= es; i--) {
                                if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
                                    start--;
                                    es--;
                                }
                            }
                        }else{
                            var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
                            while ((surrogatePairs.exec(str)) != null) {
                                var li = surrogatePairs.lastIndex;
                                if(li - 2 < start) {
                                    start++;
                                }else{
                                    break;
                                }
                            }
                        }

                        if(start >= end || start < 0) {
                            return false;
                        }
                        if(len < 0) {
                        for (i = end - 1, el = (end += len); i >= el; i--) {
                            if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
                                end--;
                                el--;
                            }
                        }
                        if(start > end) {
                            return false;
                        }
                        return str.slice(start, end);
                        }else{
                            se = start + len;
                        for(i = start; i < se; i++) {
                            ret += str.charAt(i);
                            if(/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
                                se++;
                            }
                        }
                            return ret;
                        }
                        break;
                    }
                case 'off':
                
                default:
                    if(start < 0) {
                        start += end;
                    }
                    end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
                    return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
                }
                return undefined;
            },
            strlen: function(string) {
                var str = string + '';
                var i = 0,chr = '',lgth = 0;
                var unicode_semantics = 'on';
                if (unicode_semantics !== 'on') {
                    return string.length;
                }
                var getWholeChar = function (str, i) {
                var code = str.charCodeAt(i);
                var next = '',prev = '';
                if (0xD800 <= code && code <= 0xDBFF) {
                    if (str.length <= (i + 1)) {
                        throw 'High surrogate without following low surrogate';
                    }
                    next = str.charCodeAt(i + 1);
                    if (0xDC00 > next || next > 0xDFFF) {
                        throw 'High surrogate without following low surrogate';
                    }
                    return str.charAt(i) + str.charAt(i + 1);
                }else if (0xDC00 <= code && code <= 0xDFFF) {
                    if (i === 0) {
                        throw 'Low surrogate without preceding high surrogate';
                    }
                prev = str.charCodeAt(i - 1);
                if (0xD800 > prev || prev > 0xDBFF) {
                    throw 'Low surrogate without preceding high surrogate';
                }
                    return false;
                }
                    return str.charAt(i);
                };

                for(i = 0, lgth = 0; i < str.length; i++) {
                    if((chr = getWholeChar(str, i)) === false) {
                        continue;
                    }
                    lgth++;
                }
                return lgth;
            },
            createEmail: function(data){
                if($(data).attr('data-email') != ""){
                    $("body").append("<div id='dialog'></div>");
                    var html = "<form action='' method='POST' id='dialogSendMail'>";
                    html = html+"<p><label for='subject'>Subject<em>*</em></label>";
                    html = html+"<input type='text' name='subject' id='subject' class='text ui-widget-content ui-corner-all'></p>";
                    html = html+"<p><label for='messages'>Messages<em>*</em></label>";
                    html = html+"<textarea name='messages' id='messages' class='text ui-widget-content ui-corner-all'></textarea></p>";
                    html = html+"</form>";
                    $("#dialog").empty().append(html);
                    $.fx.speeds._default = 1000;
                    $("#dialog").dialog({
                        autoOpen: false,
                        closeOnEscape: true,
                        draggable: false,
                        resizable: false,
                        width: 420,
                        show: 'explode',
                        hide: 'explode',
                        modal: true,
                        title: 'Create Email',
                        buttons: {
                            Send :function() {
                                if($("#subject").val()==""){
                                    $("#subject").addClass('error_input');
                                    $("#subject").addClass("ui-state-error");
                                    return false;
                                }
                                if($("#messages").val()==""){
                                    $("#messages").addClass('error_input');
                                    $("#messages").addClass("ui-state-error");
                                    return false;
                                }
                                $(".ui-dialog-buttonpane").append("<div class='loading_ajax'></div>");
                                $('.loading_ajax').html('<img src="'+ajax_script.ajax_image+'ajax-loader.gif"/>').fadeIn(500);
                                $.post(ajax_script.ajaxurl,{
                                    action: "createEmailAJAX",
                                    email: $(data).attr('data-email'),
                                    subject: $("#subject").val(),
                                    messages: $("#messages").val(),
                                    template: $(data).attr('data-template')
                                },function(create_email){
                                    if(create_email.success == true){
                                        $('.loading_ajax').fadeOut();
                                        $('#subject').val('');
                                        $('#messages').val('');
                                    }else{
                                        alert("Can't sending");
                                        return false;
                                    }
                                });
                            },
                            Cannel : function() {
                                $(this).dialog('close');
                            }
                        }
                    });
                    $("#dialog").dialog("open");
                }else{
                    alert("Email is empty");
                    return false;
                }
            }
        },
    }
})(jQuery, izwebz);
izwebz.core.facebook.init('745967472092415');